#include "SwipeStackWidget.h"
#include "qevent.h"

void SwipeStackWidget::mousePressEvent(QMouseEvent *event)
{
    this -> startPos = event -> pos();
}

void SwipeStackWidget::mouseMoveEvent(QMouseEvent *event)
{
    // 识别滑动
    if (event->buttons() & Qt::LeftButton && this -> moving == false) {
        int dx = event->pos().x() - this -> startPos.x();
        if (dx > 50) {                  // 右滑
            slideToIndex((currentIndex() - 1 + count()) % count(), true);
            startPos = event->pos();
        } else if (dx < -50) {          // 左滑
            slideToIndex((currentIndex() + 1) % count(), false);
            startPos = event->pos();
        }
    }
}

void SwipeStackWidget::slideToIndex(int index, bool slideRight)
{
    this -> moving = true;

    QWidget *currentWidget = this->currentWidget();
    QWidget *nextWidget = widget(index);

    int width = this->width();
    int offset = slideRight ? -width : width;

    nextWidget->setGeometry(offset, 0, width, this->height());
    nextWidget->show();

    // 当前页面滑出
    QPropertyAnimation *currentAnim = new QPropertyAnimation(currentWidget, "pos");
    currentAnim->setDuration(300);
    currentAnim->setStartValue(QPoint(0, 0));
    currentAnim->setEndValue(QPoint(-offset, 0));

    // 下一个页面滑入
    QPropertyAnimation *nextAnim = new QPropertyAnimation(nextWidget, "pos");
    nextAnim->setDuration(300);
    nextAnim->setStartValue(QPoint(offset, 0));
    nextAnim->setEndValue(QPoint(0, 0));

    currentAnim ->  start(QAbstractAnimation::DeleteWhenStopped);
    nextAnim    ->  start(QAbstractAnimation::DeleteWhenStopped);

    connect(nextAnim, &QPropertyAnimation::finished, this, [this, index, currentWidget]() {
        setCurrentIndex(index);
        currentWidget->hide();
        // 发送信号
        emit pageChanged(index);
    });

    this -> moving = false;
}
